#!/urs/bin/python3
# -*-coding:utf-8-*

from fabric.api import *
# from fabric.conrib.files import *

# env.hosts = [
#     'vm145@192.168.188.145',
# ]
#
# env.passwords = {
#     'vm145@192.168.188.145': '123456'
# }


env.hosts = [
    'hj@192.168.40.137',
]

env.passwords = {
    'hj@192.168.40.137': '110139'
}

env.sdir = "/home/hj/test/VPN"

# env.sdir = "/home/vm145/VPN/test/"
env.username = 'jiao.huang'
env.email = 'jiao.huang@rusell.top'
env.gitlab_url = 'https://192.168.188.139/python/VPN.git'


def test_exist_dir():
    """检查仓库是否存在"""
    cd(env.sdir)
    if int(run("[ -e '%s' ] && echo 11 || echo 10" % env.sdir)) == 11:
        result = True
    else:
        result = False
    return result

@task
def git_config():
    """配置 git，只需配置一次"""
    try:
        run('git config --global user.name %s' % env.username)
        run('git config --global user.email %s' % env.email)
        # run('git remote add origin %s' % env.gitlab_url)
    except Exception as e:
        print(e)


def make_dir():
    """目录不存在，则创建，初始化仓库，并将代码拉取到仓库"""
    sudo('mkdir -p %s;git init' % env.sdir)
    git_config()
    run('cd %s;git clone %s' % (env.sdir, env.gitlab_url))


def get_file():
    """若仓库存在，则更新"""
    # dir_name = env.sdir + env.gitlab_url.split('/')[-1].split('.')[0]

    run('cd %s;git pull' % env.sdir)

@task
def start():
    flag = test_exist_dir()
    if flag:
        get_file()
    else:
        make_dir()

@task
def no_username_password():
    run('cd /;git config --global credential.helper store')
